﻿using Microsoft.AspNet.Identity;
using Sidvall.IdentityManager.Data;
using Sidvall.IdentityManager.Security.Entities;
using System;
using System.Threading.Tasks;

namespace Sidvall.IdentityManager.Security
{
    public class PhoneNumberTokenProvider : UserTokenProvider
    {
        private string _MessageFormat;
        public string MessageFormat
        {
            get { return _MessageFormat ?? "{0}"; }
            set { _MessageFormat = value; }
        }

        public override Task<bool> IsValidProviderForUserAsync(UserManager<AspNetUsers, string> manager, AspNetUsers user)
        {
            var isValid = !string.IsNullOrWhiteSpace(user.PhoneNumber) && user.PhoneNumberConfirmed;
            return Task.FromResult(isValid);
        }

        protected override string GetUserModifier(string purpose, IAspNetUsers user)
        {
            return "PhoneNumber:" + purpose + ":" + user.PhoneNumber;
        }

        public override Task NotifyAsync(string token, UserManager<AspNetUsers, string> manager, AspNetUsers user)
        {
            if (manager == null)
                throw new ArgumentNullException(nameof(manager));
            return manager.SendSmsAsync(user.Id, String.Format(System.Globalization.CultureInfo.CurrentCulture, this.MessageFormat, token));
        }
    }
}
